package com.shuiyun.chat.server;

import com.shuiyun.chat.config.NettyConfig;
import com.shuiyun.chat.entity.message.SendGroupMessage;
import com.shuiyun.chat.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author shuiyun
 * @program oicq
 * @description 聊天服务器
 * @create 2021-05-12 11:33
 **/
@Slf4j
@Service
public class ChatServer {

    @Autowired
    private MessageCodecHandler messageCodecHandler;
    @Autowired
    private LoginHandler loginHandler;
    @Autowired
    private LoggingHandler loggingHandler;
    @Autowired
    private SimpleChatMessageHandler simpleChatMessageHandler;
    @Autowired
    private QuitHandler quitHandler;
    @Autowired
    private SendGroupMessageHandler sendGroupMessageHandler;

    @Autowired
    private NettyConfig.NettyServerConfig serverConfig;

    public void start(){
        try {
            NioEventLoopGroup boss = new NioEventLoopGroup();
            NioEventLoopGroup worker = new NioEventLoopGroup();


            ServerBootstrap serverBootstrap = new ServerBootstrap();
            // 通道
            serverBootstrap.channel(NioServerSocketChannel.class);
            // eventLoop
            serverBootstrap.group(boss, worker);

            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    ChannelPipeline pipeline = socketChannel.pipeline();
                    //TODO 添加日志处理器 正式上线后删除
                    pipeline.addLast(loggingHandler);
                    // 定长解码器 解决半包和黏包
                    pipeline.addLast(new LengthFieldDecoder());
                    // byte加码器 使用这个必须有之前的定长解码器解决黏包和半包问题
                    pipeline.addLast(messageCodecHandler);
                    // 登录处理器
                    pipeline.addLast(loginHandler);
                    // 简单消息处理器
                    pipeline.addLast(simpleChatMessageHandler);
                    // 接收到群消息发送
                    pipeline.addLast(sendGroupMessageHandler);
                    // 退出处理器
                    pipeline.addLast(quitHandler);
                }
            });

            ChannelFuture channelFuture = serverBootstrap.bind(serverConfig.getTcpPort()).sync();

            log.info("启动netty port:{}",serverConfig.getTcpPort());

            Channel channel = channelFuture.channel();
            channel.closeFuture().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    boss.shutdownGracefully();
                    worker.shutdownGracefully();
                }
            });
        }catch (Exception e){
            log.info("netty启动失败-------",e);
        }
    }
}
